package com.campus.shop.controller.web;

import com.campus.shop.common.ConstantProperties;
import com.campus.shop.common.Errors;
import com.campus.shop.common.Result;
import com.campus.shop.utils.ToolUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description:文件上传
 * @Author: xr
 * @Date: 2023/4/5 15:36
 */
@RestController
@RequestMapping("/web/upload")
@Slf4j
public class UploadController {
    @Value("${file.uploadFolder}")
    private String ProfilePhotoMapperPath;    //图标物理存储路径

    private static final String IMAGE_UPLOAD = "imgUpload";
    private static final String IMAGE_UPLOAD_FILE = "upFile";

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload-img")
    public Result uploadImg(@RequestParam("file") MultipartFile file, @RequestParam("module") String module){
        if (file.isEmpty()) {
            return Result.error(Errors.FILE_NOT_EXIT);
        }
        String imgName = file.getOriginalFilename();
        // 解析到文件后缀，判断是否合法
        int index = imgName.lastIndexOf(".");
        String suffix = null;
        if (index == -1 || (suffix = imgName.substring(index + 1)).isEmpty()) {
            return Result.error(500,"文件后缀不能为空");
        }
        // 允许上传的文件后缀列表
        Set allowSuffix = new HashSet<>(Arrays.asList("jpg", "jpeg", "png", "gif"));
        if (!allowSuffix.contains(suffix.toLowerCase())) {
            return Result.error(500,"文件格式不正确" + suffix);
        }

        // 给文件重命名
        String fileName = ToolUtils.getRandomStr(9) + "." + file.getContentType().substring(file.getContentType().lastIndexOf("/") + 1);
        // 获取保存路径
        String path = getSavePath(module);
        try {
            File files = new File(path, fileName);
            File parentFile = files.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdir();
            }
            file.transferTo(files);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HashMap<String, Object> res = new HashMap<>();
        String img_url = module + "/" + fileName;
        res.put("fileName",img_url);
        res.put("url", ConstantProperties.hostName + img_url);
        return Result.success(res); // 返回重命名后的文件名
    }

    /**
     * 获取存储路径
     * @return
     */
    public String getSavePath(String module) {
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        // 保存目录位置根据项目需求可随意更改
        return applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\" + module;
    }

    //保存编辑器上传图片并放回路由
    public String getUploadFileUrl(MultipartFile file){
        String module = "editor";
        // 给文件重命名
        String fileName = ToolUtils.getRandomStr(8) + "." + file.getContentType().substring(file.getContentType().lastIndexOf("/") + 1);
        // 获取保存路径
        String img_path = ProfilePhotoMapperPath + module;
        try {
            File files = new File(img_path, fileName);
            File parentFile = files.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdir();
            }
            file.transferTo(files);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String img_url = "/admin/upload/" + module + "/" + fileName;
        return ConstantProperties.hostName + img_url;

    }














}
